<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ref } from 'vue'
import type { UserTable } from '@/types/user'
import { userUpdate } from '@/api/user'
import { deepCopy } from '@/util/token'
const props = defineProps<{
  dMap: Map<string, string>
  editData: UserTable
  // 刷新
  refresh: () => void
}>()
// 关闭
const emit = defineEmits<{
  (event: 'cDlg'): void
}>()

const formRules = ref<FormRules<UserTable>>({})
const formData = ref<UserTable>(deepCopy(props.editData))
// 表单dom
const elFormRef = ref<FormInstance>()
function edit() {
  elFormRef.value?.validate((d) => {
    if (d) {
      userUpdate(formData.value)
        .then((d) => {
          ElMessage.success(d.msg)
          props.refresh()
          emit('cDlg')
        })
        .catch((d) => {
          ElMessage.error(d.msg)
        })
    }
  })
}
function cancel() {
  emit('cDlg')
  props.refresh()
}
</script>

<template>
  <el-form ref="elFormRef" :model="formData" :rules="formRules" label-width="110px">
    <el-form-item required :label="(dMap.get('nickname') || 'nickname') + '：'" prop="nickname">
      <el-input
        v-model="formData.nickname"
        :placeholder="'请输入' + dMap.get('nickname') || 'nickname'"
      ></el-input>
    </el-form-item>
    <el-form-item :label="(dMap.get('email') || 'email') + '：'" prop="email">
      <el-input
        v-model="formData.email"
        :placeholder="'请输入' + dMap.get('email') || 'email'"
      ></el-input>
    </el-form-item>
    <el-form-item :label="(dMap.get('phone') || 'phone') + '：'" prop="phone">
      <el-input
        v-model="formData.phone"
        :placeholder="'请输入' + dMap.get('phone') || 'phone'"
      ></el-input>
    </el-form-item>
    <el-row>
      <el-col :span="12"
        ><el-form-item :label="(dMap.get('sex') || 'sex') + '：'" prop="sex">
          <el-select v-model="formData.sex">
            <el-option label="男" value="1" />
            <el-option label="女" value="0" />
          </el-select> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item :label="(dMap.get('status') || 'status') + '：'" prop="status">
          <el-switch
            v-model="formData.status"
            active-value="1"
            inactive-value="0"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          ></el-switch>
        </el-form-item>
      </el-col>
    </el-row>

    <div class="buttons">
      <el-button type="primary" @click="cancel">取消</el-button>
      <el-button type="success" @click="edit">保存</el-button>
    </div>
  </el-form>
</template>
<style scoped lang="less">
.buttons {
  display: flex;
  margin-top: 30px;
  justify-content: flex-end;
}
</style>
